<?php
class AddressApp extends CommonApp {
   
    public function indexAct(){
    	$this->checklogin();
    	$parent = $_SESSION['member']['id'];
    	$address = DB('address')->where("parent = '{$parent}'")->clear()->select();
    	$this->assign('address',$address);
    	//display
		$this->display();
    }

    public function modifyAct(){
    	$this->checklogin();
    	$id = My::arr2var($_GET,'id');
    	if(My::is_id($id)){
    		$result = DB('address')->where("id = '{$id}'")->clear()->find();
    		$this->assign('result',$result);
    	}
    	$this->display();
    }
   
   	//编辑添加收获地址
   	public function saveAct(){
   		//
   		if($_POST){
   			$id = My::arr2var($_POST,'id');
   			$tel = $_POST['tel'];
   			if(!My::is_string($_POST['name']))
          $this->ajaxReturn(300,'收货人填写错误!');
			  elseif(!My::is_tel($tel))
        	$this->ajaxReturn(300,'手机号码填写错误!');
        elseif(empty($_POST['region']))
        	$this->ajaxReturn(300,'请选择所在区域!');
        elseif(!My::is_string($_POST['address']))
        	$this->ajaxReturn(300,'详细地址填写错误!');
        elseif(!My::is_id($_POST['zipcode']))
        	$this->ajaxReturn(300,'邮政编码填写错误!');
        if(isset($_POST['hot'])){
        	$hot_id = DB('address')->where("hot = 1")->getField('id');
        	if(!empty($hot_id))  $result = DB('address')->where("id = '{$hot_id}'")->setField('hot','0');
        }
            //编辑
   			if(My::is_id($id)){
   				$_POST['editdate'] = date('Y-m-d H:i:s');
   				$ok = DB('address')->where("id = '{$id}'")->clear()->save($_POST);
   				if($ok) $this->ajaxReturn(200,'编辑收货地址成功!');
   				else $this->ajaxReturn(200,'编辑收货地址成功!');
   			}else{//添加
   				$_POST['parent'] = $_SESSION['member']['id'];
   				$_POST['adddate'] = date('Y-m-d H:i:s');
   				$ok = DB('address')->clear()->add($_POST);
   				if($ok) $this->ajaxReturn(200,'添加收货地址成功!');
   				else $this->ajaxReturn(300,'添加收货地址失败!');
   			}
   		}
   	}

   	//删除收货地址
   	public function deleteAct(){
   		$member = My::arr2var($_SESSION,'member');
        if(empty($member['id']))
            $this->ajaxReturn(300,"请先登录!");
   		$id = My::arr2var($_GET,'id');
   		if(My::is_id($id)){
   			$result = DB('address')->where("id = '{$id}'")->clear()->delete();
   			if($result>0)
   				$this->ajaxReturn(200,'收货地址删除成功!');
   			else
   				$this->ajaxReturn(200,'收货地址删除失败!');
   		}
   	}

   	//默认的修改
   	public function setDefaultAct(){
   		$id = $_GET['id'];//要改变成默认地址的id
   		$id2 = DB('address')->where("hot = 1")->getField('id');
   		if($id != $id2){
   			$result1 = '';
   			if(!empty($id2)){
	   			$result1 = DB('address')->where("id = '{$id2}'")->setField('hot','0');
	   		}
	   		$result = DB('address')->where("id = '{$id}'")->setField('hot','1');
	   		if($result>0 || $result1>0)
	   			$this->ajaxReturn(200,'默认地址修改成功!');
   		}
   	}
}